/* $Id: daemon.h 15 2006-12-15 23:14:45Z judas $ */

#ifndef NIH_DAEMON_H
#define NIH_DAEMON_H 1

#include <nih/cdefs.h>

BEGIN_C_DECLS

#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#if HAVE_UNISTD_H
#include <unistd.h>
#endif /* HAVE_UNISTD_H */
#if HAVE_STAT_H
#include <stat.h>
#endif /* HAVE_STAT_H */

extern inline int nih_daemon(int nochdir, int noclose)
{
	if (fork() != 0)
		exit(EXIT_SUCCESS);

	setsid();

	if (fork() != 0)
		exit(EXIT_SUCCESS);

        if (! nochdir)
                chdir("/");

	umask(0);

        if (! noclose) {
                close(STDIN_FILENO);
                close(STDOUT_FILENO);
                close(STDERR_FILENO);
        }

        return 0;
}

#if HAVE_DAEMON
#define nih_daemon(nochdir, noclose) daemon((nochdir), (noclose))
#endif

END_C_DECLS

#endif /* NIH_DAEMON_H */

